#

| Chapter 16 Where Did I Put That? |

## 16.17 Getting Directory Name from a File's Pathname

When you write shell scripts or functions, sometimes you have a file's absolute pathname but need the parent directory's name. (You might need the parent's name to see if you have write permission in the directory - say, to remove or rename the file.)

If the pathname is stored in a csh shell (not environment) variable, use the modifier `:h` (9.6). In the Bourne shell, see if your system has the dirname (45.18) command. If it doesn't, you can get the GNU version from the Power Tools disc - or use expr (45.28) with a regular expression (26.4) that gives you everything up to (but not including) the last slash. For example, if the pathname /home/mktg/fred/afile is stored in the shell variable file, these csh and sh commands would store /home/mktg/fred into the variable dir:

>     % set dir=$file:h
>     $ dir=`dirname "$file"`
>     $ dir=`expr "$file" : '\(.*\)/'`

To handle multiple pathnames, give this regular expression to sed (34.24):

    @
    % ... sed 's@/[^/]*$@@' ...

- JP

16.16 Picking a Unique Filename Automatically |  | 16.18 Listing Files You've Created/Edited Today